import uuid
import os
import base64
import requests
from PIL import Image
import imgUtils


def downloadImg(imageUrl=None, savePath=None, encodeAble=False, openProxy=False):
    img = None  # 图片转换后的base64
    """首先下载图片
    encodeAble 是否编码成base64(带前缀) 否的话则直接返回PIL的Image对象会返回图片的path和name"""
    # try:
    # printListener is not None and printListener("fjdiosfjiosdjfgoidso")
    if imageUrl is None:
        raise

    fileName = str(uuid.uuid4()).replace('-', '') + \
               os.path.splitext(imageUrl)[-1]
    filePath = savePath + fileName

    # 配置proxies字典
    proxies = {
        'http': 'http://127.0.0.1:7890',
        'https': 'http://127.0.0.1:7890'
    }
    # printListener is not None and printListener("图片文件本地保存地址" + filePath)
    # 文件下载
    # imageUrl = "https://qiniu.menghuanai.com/00000fd5-3130-11ee-b293-00e01cc664b.jpg"
    if openProxy:
        res = requests.get(imageUrl, stream=True, timeout=10,
                           proxies=proxies)
    else:
        res = requests.get(imageUrl, stream=True, timeout=10)

    with open(r'' + filePath, "wb") as pyFile:
        for chunk in res.iter_content(chunk_size=1024):
            if chunk:
                pyFile.write(chunk)

    # if encodeAble:
    #     img = base64.b64encode(open(filePath, 'rb').read())
    #     s = img.decode()
    #     img = 'data:image/jpeg;base64,%s' % s
    #     return img
    # else:
    img = Image.open(filePath)  # 读取数据
    if encodeAble:
        img = imgUtils.pil_base64_prefix(img)
    return img, filePath, fileName
